package com.learn.mvc.handler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

@Controller
public class Demo02AttrHandler {
    Logger logger = LoggerFactory.getLogger(this.getClass());

    // /attr/request/model}">测试通
    // /attr/request/map}">测试通过
    // /attr/request/modelMap}">
    // /attr/request/original}">
    // /attr/request/mav}">测试通过

    @RequestMapping("/attr/request/model")
    public String testAttrRequestModel(
            // 在形参位置声明Model类型变量，用于存储模型数据
            Model model
    ) {
        // 我们将数据存入模型，SpringMVC 会帮我们把模型数据存入请求域
        // 存入请求域这个动作也被称为暴露到请求域
        model.addAttribute("requestScopeMessageModel", "i am very happy[model]");

        return "target";
    }

    @RequestMapping("/attr/request/map")
    public String testAttrRequestMap(
            // 在形参位置声明Map类型变量，用于存储模型数据
            Map<String, Object> map
    ) {
        map.put("requestScopeMessageMap", "i am very happy[map]");
        return "target";
    }

    @RequestMapping("/attr/request/modelMap")
    public String testModelMap(ModelMap modelMap) {

        modelMap.addAttribute("requestScopeMessageModelMap", "i am very happy[model map]");
        return "target";
    }

    @RequestMapping("/attr/request/original")
    public String testOriginal(
            HttpServletRequest request
    ) {
        request.setAttribute("requestScopeMessageOriginal", "i am very happy[original]");
        return "target";
    }

    @RequestMapping("/attr/request/mav")
    public ModelAndView testModelAndView() {
        // 1.创建ModelAndView对象
        ModelAndView modelAndView = new ModelAndView();
        // 2.存入模型数据
        modelAndView.addObject("requestScopeMessageModelAndView", "i am very happy[model and view]");
        // 3.设置视图名称
        modelAndView.setViewName("target");
        return modelAndView;
    }

    @RequestMapping("/attr/session")
    public String attrSession(
            // 使用会话域最简单最直接的方式就是使用原生的 HttpSession
            HttpSession session
    ) {
        session.setAttribute("sessionScopeMessage", "I am haha...");
        return "target";
    }
    @Autowired
    private ServletContext servletContext;
    @RequestMapping("/attr/application")
    public String attrApplication() {
        servletContext.setAttribute("applicationScopeMessage", "I am very happy...");
        return "target";
    }

}
